package com.woyou.ui.fragment;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.citaq.ideliver.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.woyou.Constant;
import com.woyou.bean.Info;
import com.woyou.bean.MyAddress;
import com.woyou.bean.MyOrderItem;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.MD5Req;
import com.woyou.service.LocationLoopService;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.activity.ActivitiesActivity_;
import com.woyou.ui.activity.AppProblemActivity_;
import com.woyou.ui.activity.HomeActivity_;
import com.woyou.ui.activity.LoginActivity_;
import com.woyou.ui.activity.MyInfoActivity_;
import com.woyou.ui.activity.ShopInfoActivity;
import com.woyou.ui.activity.SpecificShopsActivity_;
import com.woyou.ui.activity.orderdetail.OrderDetailActivity;
import com.woyou.ui.activity.orderlist.MyOrderActivity;
import com.woyou.ui.component.ErrorHintView;
import com.woyou.utils.DesUtils;
import com.woyou.utils.Utils;
import com.woyou.utils.eventbus.EventHideUpdate;
import com.woyou.utils.eventbus.EventShowBar;

import de.greenrobot.event.EventBus;

/**
 * 主页
 * 
 * @author longtao.li
 */
@EFragment(R.layout.fm_index)
public class IndexFragment extends SuperFragment {

	private static final String TAG = "IndexFragment";

	FragmentManager fm;
	FragmentTransaction ft;
	@ViewById(R.id.webview)
	WebView mWeb;

	@ViewById(R.id.hintView)
	ErrorHintView hintView;

	@Override
	void showProgressDialog() {
		if (hintView != null)
			hintView.loadingData();
	}

	@Override
	void dismissProgressDialog() {
		hintView.hideLoading();
	}

	private BDLocation mlocation;
	private MyLocationListener mListener;

	@AfterViews
	void init() {
		showProgressDialog();
		mListener = new MyLocationListener();
		mBaiduLocationService.registerLocationListenner(mListener);
		mBaiduLocationService.startLocation();
	}

	class Params {
		public String uId;
		public String pwd;
		public String lat;
		public String lng;
		public String cityName;
		public String phone;
		public String deviceType;
		public String versionCode;
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (!hidden) {
			if (LocationLoopService.getInstance(mContext).getChosenAddr() != null) {
				refreshUI_B();
			}
			refreshUI_A();
			EventBus.getDefault().post(new EventShowBar(1));
		} else {
			EventBus.getDefault().post(new EventHideUpdate(1));
		}

	}

	/**
	 * 返回当前程序版本名
	 */
	public String getAppVersionName(Context context) {
		String versionName = "";
		try {
			// ---get the package info---
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;
			if (versionName == null || versionName.length() <= 0) {
				return "";
			}
		} catch (Exception e) {
		}
		return versionName;
	}

	/**
	 * 刷新跟用户信息相关的界面
	 */
	public void refreshUI_A() {
		UserInfo userInfo = mUserModel.getUserInfo();
		Params params = new Params();
		if (userInfo != null) {
			params.uId = userInfo.getuId();
			params.pwd = userInfo.getPwd();
		} else {
			params.uId = "";
			params.pwd = "";
		}

		// MyAddress serarchAddr =
		// LocationLoopService.getInstance(mContext).getChosenAddr();
		// if( serarchAddr == null ){
		// if( mlocation == null ){
		// params.lat = "";
		// params.lng = "";
		// }else{
		// params.lat = mlocation.getLatitude()+"";
		// params.lng = mlocation.getLongitude() + "";
		// if( mlocation.getCity()!= null ){
		// params.cityName = mlocation.getCity();
		// }
		// }
		// }else{
		// params.lat = serarchAddr.getLat();
		// params.lng = serarchAddr.getLng();
		// if( serarchAddr.getCityName()!= null ){
		// params.cityName = serarchAddr.getCityName();
		// } else {
		// params.cityName = "";
		// }
		// }

		try {
			String jsonParams = new Gson().toJson(params);
			jsonParams = jsonParams.replace(" ", "");
			String json = DesUtils.encode(DesUtils.key, jsonParams);
			json = URLEncoder.encode(json, "utf-8");
			String js = "javascript:refreshUI_A('" + json + "')";
			mWeb.loadUrl(js);
		} catch (Exception e) {
			e.printStackTrace();
			Log.d("index view", "GSON parse error");
		}

		// MD5Req<Params> req = new MD5Req<Params>(params);
		// String json = new Gson().toJson(req);
		// String js = "javascript:refreshUI_A("+json+")";
		// mWeb.loadUrl(js);
	}

	/**
	 * 刷新跟地址相关的界面
	 */
	public void refreshUI_B() {
		Params params = new Params();
		UserInfo userInfo = mUserModel.getUserInfo();
		if (userInfo != null) {
			// params.uId = userInfo.getuId();
			// params.pwd = userInfo.getPwd();
			params.phone = userInfo.getPhone();
		} else {
			// params.uId = "";
			// params.pwd = "";
			params.phone = "";
		}

		MyAddress serarchAddr = LocationLoopService.getInstance(mContext).getChosenAddr();
		if (serarchAddr == null) {
			params.lat = "";
			params.lng = "";
		} else {
			params.lat = serarchAddr.getLat();
			params.lng = serarchAddr.getLng();
			if (serarchAddr.getCityName() != null) {
				params.cityName = serarchAddr.getCityName();
			} else {
				params.cityName = "";
			}
		}

		try {
			String jsonParams = new Gson().toJson(params);
			jsonParams = jsonParams.replace(" ", "");
			String json = DesUtils.encode(DesUtils.key, jsonParams);
			json = URLEncoder.encode(json, "utf-8");
			String js = "javascript:refreshUI_B('" + json + "')";
			mWeb.loadUrl(js);
		} catch (Exception e) {
			e.printStackTrace();
			Log.d("index view", "GSON parse error");
		}
	}

	public void initView(BDLocation location) {
		if (location == null) {
			return;
		}
		String url = "http://" + Constant.WEB_SERVER + "/MainPage"; // 正式的服务器
		UserInfo userInfo = mUserModel.getUserInfo();
		Params params = new Params();
		params.uId = userInfo.getuId();
		params.pwd = userInfo.getPwd();
		params.deviceType = "android";
		String versionName = getAppVersionName(mActivity);
		params.versionCode = versionName;
		if (location != null) {
			params.lat = location.getLatitude() + "";
			params.lng = location.getLongitude() + "";
			if (location.getCity() != null) {
				params.cityName = location.getCity();
			}
		}
		MD5Req<Params> req = new MD5Req<Params>(params);
		try {
			url = Utils.getWebUrl(url, req);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		initWebView(url);
	}

	public void refreshInitView(String cityName, String lat, String lng) {
		String url = "http://" + Constant.WEB_SERVER + "/MainPage"; // 正式的服务器
		UserInfo userInfo = mUserModel.getUserInfo();
		Params params = new Params();
		params.uId = userInfo.getuId();
		params.pwd = userInfo.getPwd();
		params.deviceType = "android";
		String versionName = getAppVersionName(mActivity);
		params.versionCode = versionName;
		if (!cityName.equals("") && !lat.equals("") && !lng.equals("")) {
			params.lat = lat;
			params.lng = lng;
			params.cityName = cityName;
		} else {
			params.lat = "";
			params.lng = "";
			params.cityName = "";
		}
		MD5Req<Params> req = new MD5Req<Params>(params);
		try {
			url = Utils.getWebUrl(url, req);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		initWebView(url);
	}

	class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			mBaiduLocationService.stop();
			mBaiduLocationService.unRegisterLocationListener(mListener);
			Log.i("onReceiveLocation", "onPageFinished");
			dismissProgressDialog();
			if (location != null) {
				mlocation = location;
				initView(mlocation);
			}
		}

	}

	@SuppressLint("SetJavaScriptEnabled")
	private void initWebView(String url) {
		// 如果访问的页面中有Javascript，则webview必须设置支持Javascript
		mWeb.getSettings().setJavaScriptEnabled(true);
		mWeb.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		// mWeb.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		// 触摸焦点起作用
		mWeb.requestFocus();
		// 取消滚动条
		mWeb.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		// 设置WevView要显示的网页：
		mWeb.loadUrl(url);
		// 设置不可缩放
		mWeb.getSettings().setSupportZoom(false);
		mWeb.getSettings().setBuiltInZoomControls(false);

		mWeb.setWebViewClient(new MyWebViewClient());
		mWeb.setWebChromeClient(new WebChromeClient());
		mWeb.addJavascriptInterface(this, "ideliver");
	}

	class MyWebViewClient extends WebViewClient {

		private boolean flag;

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (!TextUtils.isEmpty(url)) {
				flag = true;
				Log.i("shouldOverrideUrlLoading", "onPageFinished");
				view.loadUrl(url);
			}
			return false;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			dismissProgressDialog();
			String title = view.getTitle();
			if (TextUtils.isEmpty(title)) {
				return;
			}
			Log.i(TAG, "onPageFinished");
			if (!title.contains("ideliver") || !flag && (!url.equals("file:///android_asset/no_network.html")
					&& !url.equals("file:///android_asset/load_failed.html"))) {
				if (!NetWorkCenter.isNetworkConnected(mContext)) {
					view.loadUrl("file:///android_asset/no_network.html");
				} else {
					view.loadUrl("file:///android_asset/load_failed.html");
				}
				view.addJavascriptInterface(IndexFragment.this, "ideliver");
			}
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			Log.i("onReceivedError", "onReceivedError");
			// Message message=myhandler.obtainMessage();
			// myhandler.sendMessage(message);
			flag = false;
		}

	}

	/**
	 * JS端发送消息到android
	 * 
	 * @param message
	 */
	@SuppressWarnings("rawtypes")
	public void messageFromJS(String message) {
		UserInfo userInfo = mUserModel.getUserInfo();
		try {
			JSONObject msg = new JSONObject(message);
			String type = msg.getString("messageType");
			if ("orderList".equals(type)) {
				// 查看订单列表
				Info<String> info = new Info<String>();
				info.setOrigin(IndexFragment_.class);
				openActivity(MyOrderActivity.class, info);

			} else if ("orderDetails".equals(type)) {
				// 查看订单详情
				String params = msg.getString("params");
				JSONObject jsonObject = new JSONObject(params);
				String oId = jsonObject.getString("oId");
				MyOrderItem order = new MyOrderItem();
				order.setoId(oId);

				Info<MyOrderItem> info = new Info<MyOrderItem>();
				info.setData(order);
				info.setOrigin(IndexFragment_.class);
				openActivity(OrderDetailActivity.class, info);

			} else if ("feedback".equals(type)) {
				// 跳转到用户反馈界面消息
				openActivity(AppProblemActivity_.class, null);

			} else if ("tryAgain".equals(type)) {
				showProgressDialog();
				mBaiduLocationService.registerLocationListenner(mListener);
				mBaiduLocationService.startLocation();

			} else if ("browseShops".equals(type)) {
				if (!isHidden()) {
					// 跳转到店铺列表界面
					Info<Class> info = new Info<Class>();
					info.setData(ShopsFragment_.class);
					openActivity(HomeActivity_.class, info);
				}

			} else if ("browseShops2".equals(type)) {
				// 跳转到店铺列表界面（全部优惠）
				Info<Class> info = new Info<Class>();
				info.setData(ShopsFragment_.class);
				info.setOrigin(IndexFragment_.class);
				openActivity(HomeActivity_.class, info);

			} else if ("selectAd".equals(type)) {
				// 跳转到广告界面
				String params = msg.getString("params");
				JSONObject jsonObject = new JSONObject(params);
				String webUrl = jsonObject.getString("AdUrl");
				String list = jsonObject.getString("codeList");
				if (!TextUtils.isEmpty(webUrl) && URLUtil.isHttpUrl(webUrl)) {
					webUrl = webUrl + "/stPhone=" + userInfo.getPhone() + "/stLng=" + mlocation.getLongitude()
							+ "/stLat=" + mlocation.getLatitude() + "/platform=android" + "/version="
							+ GetVersion(mContext);
					Info<String> info = new Info<String>();
					info.setData(webUrl);
					info.setOrigin(IndexFragment_.class);
					openActivity(ActivitiesActivity_.class, info);

				} else if (!TextUtils.isEmpty(list)) {
					Gson gson = new Gson();
					List<String> codeList = gson.fromJson(list, new TypeToken<List<String>>() {
					}.getType());
					if (codeList != null && codeList.size() > 1) {
						// 跳转到特殊的活动店铺
						Info<List<String>> info = new Info<List<String>>();
						info.setData(codeList);
						info.setOrigin(IndexFragment_.class);
						openActivity(SpecificShopsActivity_.class, info);

					} else if (codeList != null && codeList.size() == 1) {
						// 跳转到店铺详情
						String sId = codeList.get(0);
						Info<String> info = new Info<String>();
						info.setData(sId);
						info.setOrigin(IndexFragment_.class);
						openActivity(ShopInfoActivity.class, info);

					}

				}
			} else if ("userclick".equals(type)) {
				if (userInfo.getuId() != null && !userInfo.getuId().equals("")) {
					// 点击头像判断用户是否登录，登录到个人信息
					openActivity(MyInfoActivity_.class, null);

				} else {
					// 未登录到登录
					Info<String> info = new Info<String>();
					info.setOrigin(IndexFragment_.class);
					openActivity(LoginActivity_.class, info);

				}
				
			} else if ("cityClick".equals(type)) {
				String params = msg.getString("params");
				JSONObject jsonObject = new JSONObject(params);
				String name = jsonObject.getString("name");
				String lat = jsonObject.getString("lat");
				String lng = jsonObject.getString("lng");
				refreshInitView(name, lat, lng);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 取得版本号
	 * 
	 * @param context
	 * @return
	 */
	public static String GetVersion(Context context) {
		try {
			PackageInfo manager = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return manager.versionName;
		} catch (NameNotFoundException e) {
			return "Unknown";
		}
	}

	@Override
	public void retry() {

	}

	@Override
	public void pwdError() {

	}

	@Override
	protected void obtainInfo() {

	}

	@Override
	public void netError() {

	}

}
